package com.itcast.common.utils;


import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 阿里云-SMS短信发送工具类
 */

@Component
public class SMSUtils {
    //短信模板code
    public static final String VALIDATE_CODE = "SMS_154950909"; //发送短信验证码  阿里云短信测试模板
    public static final String ORDER_NOTICE = "SMS_159771588";//体检预约成功通知

    private static String accessKeyId = "xxxxxx";
    private static String accessKeySecret = "xxxxxx";

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信
     * @param phoneNumbers
     * @param param
     * @throws Exception
     */
    public static void  sendShortMessage(String templateCode,String phoneNumbers,String param) {

        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            System.out.println("accessKeyId:" + accessKeyId);
            client = SMSUtils.createClient(accessKeyId, accessKeySecret);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("阿里云短信测试")
                    .setTemplateCode(templateCode)
                    .setPhoneNumbers(phoneNumbers)
                    .setTemplateParam("{\"code\":\"" + param + "\"}");
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (sendSmsResponse.getBody().getCode().equals("OK")){
                System.out.println("sendSms请求成功");
            }else {
                System.out.println("请求失败 Code："+sendSmsResponse.getBody().getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
